﻿using Common.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace GYMm.UI.Controls
{
	public sealed partial class Input : UserControl
	{
		public Double Value
		{
			get { return (Double)GetValue(ValueProperty); }
			set { SetValue(ValueProperty, value); }
		}

		public static readonly DependencyProperty ValueProperty =
			DependencyProperty.Register("Value", typeof(Double), typeof(Input), new PropertyMetadata(0, OnValueChanged));

		private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			(d as Input).UpdateValue();
		}



		public String Label
		{
			get { return (String)GetValue(LabelProperty); }
			set { SetValue(LabelProperty, value); }
		}

		public static readonly DependencyProperty LabelProperty =
			DependencyProperty.Register("Label", typeof(String), typeof(Input), new PropertyMetadata("", OnLabelChanged));

		private static void OnLabelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			(d as Input).UpdateLabel();
		}


		public Double Step
		{
			get { return (Double)GetValue(StepProperty); }
			set { SetValue(StepProperty, value); }
		}

		public static readonly DependencyProperty StepProperty =
			DependencyProperty.Register("Step", typeof(Double), typeof(Input), new PropertyMetadata(1.0));



		public String Format
		{
			get { return (String)GetValue(FormatProperty); }
			set { SetValue(FormatProperty, value); }
		}

		public static readonly DependencyProperty FormatProperty =
			DependencyProperty.Register("Format", typeof(String), typeof(Input), new PropertyMetadata("N2", OnFormatChanged));

		private static void OnFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			(d as Input).UpdateValue();
		}



		public Input()
		{
			this.InitializeComponent();
		}

		private void UpdateValue()
		{
			try
			{
				ValueTB.Text = Value.ToString(Format);
			}
			catch
			{
				Value = 0.0;
			}
		}



		private void UpdateLabel()
		{
			LabelTB.Text = Label;
		}

		private void DownClicked(object sender, RoutedEventArgs e)
		{
			Value = Math.Max(0.0, Value - Step);
		}

		private void UpClicked(object sender, RoutedEventArgs e)
		{
			Value += Step;
		}
	}
}
